/**
 * 纵道软件
 * 版本：v1.0
 */
var ZD = ZD || {};

/*======================基础变量部分 start============================*/
ZD.base = {};
ZD.base.TOKEN = "token_value_0"; /*token存储的Cookie的名称*/
ZD.base.TableCLiCkcheck = true; /*网格是否可多选*/
ZD.base.Template = {}; /*缓存的html模板*/
ZD.base.IMGSUF = "gif,jpeg,jpg,png"; /*图片的后缀*/
ZD.base.RightFuncHide = true; /*无权限的按钮是否隐藏*/
ZD.base.ID = "id"; /*网格的主键ID*/
/*======================基础变量部分 end============================*/


/*======================方法部分 start============================*/
ZD.ux = {};
/*普通的Ajax请求
 * option.data需要为json对象
 * */
ZD.ux.Ajax = function(option){
	
	//获取URL
	var protocol = window.location.protocol;
	var host = window.location.host;
	var url = protocol + '//' + host + '/finance/router/rest';
	
	var token = ZD.ux.GetCookie(ZD.base.TOKEN); /*token存放的值*/
	option.data = option.data||{};
	if(token != null){
		option.data.token = token;
	}
	var fdata = JSON.stringify(option.data);
	$.ajax({
		url:url,
		data:fdata,
		type:option.type||"POST",
		async:(option.async==null || option.async==undefined?true:false),
		dataType:option.dataType||"json",
		contentType:"application/json",
		beforeSend:function(request){
			request.setRequestHeader("token", token);
		},
		success:option.success,
		error:option.error
	});
};

/*打印对象*/
ZD.ux.PrintValue = function(obj){
	var description = "";
	for(var i in obj){
		var property=obj[i];
		description+=i+" = "+property+"\n";
	}
	alert(description);
}

/*获得浏览器参数*/
ZD.ux.GetQueryString = function(name){
	var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i"); 
	var r = window.location.search.substr(1).match(reg); 
	if (r != null) return unescape(r[2]); return null; 
}

/*时间的转换*/
ZD.ux.GetSec = function(str){
	var str1=str.substring(1,str.length)*1;
	   var str2=str.substring(0,1);
	   if (str2=="s"){
	        return str1*1000;
	   }
	   else if (str2=="h"){
	       return str1*60*60*1000;
	   }
	   else if (str2=="d"){
	       return str1*24*60*60*1000;
	   }else{
		   return 24*60*60*1000;
	   }
}

/*设置cookies
 * name:名称
 * value:值
 * time:s20是代表20秒,h是指小时,如12小时则是：h12,d是天数，30天则：d30 
 * */
ZD.ux.SetCookie = function(name,value,time){
	var strsec = ZD.ux.GetSec(time);
    var exp = new Date();
    exp.setTime(exp.getTime() + strsec*1);
    document.cookie = name + "="+ escape (value) + ";expires=" + exp.toGMTString()+";path=/";
}

/*获得cookies*/
ZD.ux.GetCookie = function(name){
	var arr,reg=new RegExp("(^| )"+name+"=([^;]*)(;|$)");
    if(arr=document.cookie.match(reg))
        return unescape(arr[2]);
    else 
        return null;
//    	return 'asdfgh1234';
}

/*转换date*/
ZD.ux.GetDate = function(strDate){
	var date = eval('new Date(' + strDate.replace(/\d+(?=-[^-]+$)/,
			function (a) { return parseInt(a, 10) - 1; }).match(/\d+/g) + ')');
	return date;
}

/*验证表单框是否符合表达式*/
ZD.ux.Verify = function(v){
	var bl = true;
	var _objs = "";
	if(v){
		_objs = $(v+" input,"+v+" select,"+v+" div");
	}else{
		_objs = $("input,select,div");
	}
	var blScroll = false;
	_objs.each(function(){
		var fverify = $(this).attr("data-verify");
		var fverify_text = $(this).attr("data-verify_text");
		if(!fverify || fverify.length == 0){
			return true;
		}
		var fval = $(this).val();
		if($(this).is("div")){
			fval = $(this).summernote("code");
		}
		var f = ZD.verify.Range(fverify);
		if(!f.test(fval)){
			$(this).tips({
				side:3,
				msg:fverify_text,
				time:3
			});
			if(!blScroll){
				$("html,body").animate({
	                scrollTop: $(this).offset().top-10
	            },500);
				blScroll = true;
			}
			
			bl = false;
		}
	});
	return bl;
}

/*给iframe设置src值(打开url)*/
ZD.ux.OpenMenuUrl = function(fheader,furl){
	if(!furl || furl==undefined || furl==null || furl.length==0){
		return;
	}
	if(document.getElementById("sysfram")){
		document.getElementById("sysfram").src = fheader + furl;
	}else{
		parent.document.getElementById("sysfram").src = fheader + furl;
	}
	
}

/*根据html模板生成html*/
ZD.ux.Rephtml = function(res,_html){
	var reg = /{{([A-Za-z0-9_]+)}}/gm,
    reg_fun = /\[\[([A-Za-z0-9_]+)\:([\S\s]*?)\]\]/gm;
	var html = '';
	for(var i=0;i<res.length;i++){
		if(!res[i]){
			continue;
		}
		html += _html.replace(reg,function(patt, $1){
			if($1 == "rowIndex"){
				return (i + 1);
			}else{
				if(res[i][$1] != null && typeof(res[i][$1]) == "object"){
					var html = "{";
					for(var key in res[i][$1]){
						if(html.length > 1){
							html += ",'"+key+"':'"+res[i][$1][key]+"'";
						}else{
							html += "'"+key+"':'"+res[i][$1][key]+"'";
						}
					}
					html += "}";
					return html;
				}
				return (res[i][$1]==null || res[i][$1]==undefined ? "":res[i][$1]);
			}
		}).replace(reg_fun, function (patt, $1, $2) {
            return window[$1].apply(this, ($2.split(",")));
        });
	}
	return html;
}

/*分页查询数据(适用于后台...) **/
ZD.ux.BindGrid = function(option){
	/*table内容区*/ 
	var _obj = $("#"+option.table);
	//创建一个存放数据源的对象的input标签
	if($("#"+option.table+"_table_data").length <= 0){
		$("#"+option.table).parent().append('<input type="hidden" id="'+option.table+'_table_data" />');
	}
	
	var paging = option.paging; /*是否分页...*/
	if(paging == undefined || paging == null){
		paging = true;
	}
	
	var dynamic = option.dynamic; /*动态表头*/
	if(dynamic == undefined || dynamic == null){
		dynamic = false;
	}
	
	var _tds = 0;
	var _html = '';
	/*缓存html模板z和td数*/
	if(ZD.base.Template[option.table] == undefined || option.dynamic){
		ZD.base.Template[option.table] = _html = _obj.html();
		ZD.base.Template[option.table+"_tds"] = _tds = _obj.find("td").length;
	}else{
		_html = ZD.base.Template[option.table];
		_tds = ZD.base.Template[option.table+"_tds"];
	}
	var l = ZD.msg.load();
	/*回调...*/
	option.success = function(res){
		ZD.msg.close(l);
		if(res.status == 0){
			//赋值网格的data对象
			$("#"+option.table+"_table_data").val(JSON.stringify(res));

			/*res.data.data 分页得到的list*/
			var html = "";
			if(paging){
				html = ZD.ux.Rephtml(res.data.data,_html);
			}else{
				if(res.data.data){
					html = ZD.ux.Rephtml(res.data.data,_html);
				}else{
					html = ZD.ux.Rephtml(res.data,_html);
				}
			}
			
			if(html.length == 0){
				html = '<tr class="main_info"><td colspan = "'+ _tds +'">没有任何数据</td>';
			}
			_obj.html(html);
			var ftableId = _obj.parent().attr("id");
			ZD.ux.TableCLick(ftableId); /*行单击事件*/
			ZD.ux.TableAllCheck(ftableId); /*全选的勾选状态*/
			if(paging){
				/***=======...分页...=======***/
				option.data.totalpage = res.data.totalpage;
				option.data.totalresult = res.data.totalresult;
				ZD.ux.CreatePaging(option);
				/***=======...分页...=======***/
			}
			
			/*回调*/
			if(option.callback){
				var res = {
					table:option.table
				};
				option.callback(res);
			}
		}else{
			
		}
	}
	if(option.staticdata){
		option.success(option.staticdata);
	}else{
		ZD.ux.Ajax(option);
	}
}

/*创建分页,,,适用于后台*/
ZD.ux.CreatePaging = function(option){
	var _obj = $("#"+option.table);
	/*移除分页*/
	_obj.parent().next().remove();
	
	/*分页...*/
	var fcurrPage = parseInt(option.data.currpage);
	var ftotalPage = parseInt(option.data.totalpage);
	fcurrPage = fcurrPage==0?1:fcurrPage;
	/*分页栏*/
	var fpaging = '<form class="form-inline text-right zd_form_page_0" role="formpage"> 每页'+option.data.count+'条,共'+option.data.totalresult+'条,'+option.data.totalpage+'页 <div class="form-group "><nav><ul class="pagination">';
	fpaging += '<li><a href="javascript:void(0);" data-key="'+(fcurrPage-1)+'">&laquo;</a></li>';
	var fstart = 1;
	if(fcurrPage > 3){
		fstart = fcurrPage - 3;
	}
	var fend = ftotalPage + 1;
	if((fend - fstart) > 3){
		fend = fstart + 7;
	}
	if(fend > ftotalPage){
		fend = ftotalPage + 1;
	}
	for(var i = fstart;i < fend;i++){
		if(i == fcurrPage){
			fpaging += '<li class="active"><a href="javascript:void(0);" data-key="'+i+'">'+i+'</a></li>';
		}else{
			fpaging += '<li><a href="javascript:void(0);" data-key="'+i+'">'+i+'</a></li>';
		}
	}
	fpaging += '<li><a href="javascript:void(0);" data-key="'+(fcurrPage+1)+'">&raquo;</a></li>';
	fpaging += '</ul></nav>';
	fpaging += '</div><div class="form-group"><div class="input-group">'+
	'<input type="text" class="form-control" placeholder="页码" style="width:60px;float: right;"><span class="input-group-btn">'+
	'<button class="btn btn-small btn-primary" type="button" data-pager="goto">跳转</button>'+
	'</span></div></div></form>';
	
	/*分级...*/
	fpaging = '<div class="row" style="margin-top:-2.5em;"><div class="col-md-4"><div id="_'+option.table+'bottom_span" style="margin:20px;margin-left:0;"></div></div><div class="col-md-8">'+fpaging+'</div></div>';
	
	/*追加页码*/
	_obj.parent().parent().append(fpaging);
	
	/*监听单击事件*/
	$("nav a").click(function(){
		var ftol = parseInt(ftotalPage);
		var fnext = $(this).attr("data-key");
		if(fnext<=0 || fnext > ftol || fnext == fcurrPage){
			return;
		}
		option.data.currpage = fnext;
		ZD.ux.BindGrid(option);
	});
	
	/*页面跳转*/
	$(".zd_form_page_0 button").click(function(){
		var fval = $(this).parent().prev().val();
		if(fval.length ==0 || isNaN(fval)){
			return;
		}
		fval = parseInt(fval);
		if(fval < 1 || fval > ftotalPage){
			return;
		}
		option.data.currpage = fval;
		ZD.ux.BindGrid(option);
	});
}

/*给网格分页栏加入 扩展信息 参数：{table:"table1",text:"测试扩展."}*/
ZD.ux.InitPagingBottomSpan = function(option){
	var id = "_"+option.table+"bottom_span";
	//alert(id);
	$("#"+id).html(option.text);
}

/*网格复选框全选*/
ZD.ux.AllCheckbox = function(e){
	if(!ZD.base.TableCLiCkcheck){ return; }
	$(e).closest('table').find('tr > td:first-child input:checkbox')
	.each(function(){
		this.checked = e.checked;
		$(this).closest('tr').toggleClass('selected');
	});
}

/*网格的行单击对象*/
ZD.ux.TableCLick = function(v,c){
	var fid = '';
	if(v){
		if(v.indexOf("#") < 0){
			fid = "#"+v;
		}
	}else{
		fid = ".table";
	}
	if(c){
		/*先隐藏全选*/
		$(fid+" th label").hide();
		return;
	}
	/*隐藏 全选框*/
	if(!ZD.base.TableCLiCkcheck){
		$(fid+" th label").hide();
	}else{
		$(fid+" th label").show();
	}
	$(fid+" input[name='ids']").each(function(){
		this.onclick = function(e){
			/*设置table的勾选状态*/
			setTimeout(function(){
				ZD.ux.TableAllCheck(fid);
			},100);
			e && e.stopPropagation ? e.stopPropagation() : window.event.cancelBubble=true;
		}
		this.onchange = function(e){
			if(this.checked){
				if(!ZD.base.TableCLiCkcheck){
					$(fid+" input[name='ids']").each(function(){
						this.checked = false;
					});
				}
				this.checked = true;
			}
		}
	});
	
	/*表格选中行事件*/
	$(fid+" td").click(function(){
		if($(this).parent().find("input[name='ids']").length == 0){
			return;
		}
		
		/*单击内容体*/
		$(this).parent().find('td:first-child input:checkbox').each(function(){
			/*if(!ZD.base.TableCLiCkcheck){
				$(fid+" input[name='ids']").each(function(){
					this.checked = false;
				});
			}*/
			
			//不管是否显示多选，都先移除 再选择。单击内容体一次只能选择一条，单击复选框才是多选。
			$(fid+" input[name='ids']").each(function(){
				this.checked = false;
			});
			
			this.checked = this.checked ? false : true;
			$(this).closest('tr').toggleClass('selected');
		});
		
		/*设置table全选的勾选状态*/
		ZD.ux.TableAllCheck(fid);
		
	});
}

/*设置table的全选check的勾选状态*/
ZD.ux.TableAllCheck = function(v){
	var fid = '';
	if(v){
		if(v.indexOf("#") < 0 && v.indexOf(".") < 0){
			fid = "#"+v;
		}
	}else{
		fid = ".table";
	}
	var fcount = 0;
	$(fid+" input[name='ids']").each(function(){
		if(this.checked){
			fcount++;
		}
	});
	var fche = $(fid+" th").eq(0).find("input[type='checkbox']");
	if($(fid+" input[name='ids']").length == fcount && fcount!=0){
		fche.eq(0).prop("checked", true);
	}else{
		fche.eq(0).prop("checked", false);
	}
}

/*得到网格的数据源对象*/
ZD.ux.GetGridData = function(table){
	if(table.indexOf("#") < 0){
		table = "#"+table;
	}
	var str = $(table+"_table_data").val();
	if(!str){
		return null;
	}
	var obj = JSON.parse(str);
	return obj;
}

/*获得选中的行对象(一行)*/
ZD.ux.GetSelectdRowData = function(table){
	var obj = ZD.ux.GetGridData(table);
	var data = null;
	if(obj.data.data){
		data = obj.data.data;
	}else{
		data = obj.data;
	}
	var fids = ZD.ux.SelectedCheckboxIds(table);
	if(fids.length == 0){
		return null;
	}
	for(var i=0;i<data.length;i++){
		if(data[i][ZD.base.ID] == fids.split(",")[0]){
			return data[i];
		}
	}
	return null;
}

/*获得选中的行对象（多行）*/
ZD.ux.GetSelectdRowDatas = function(table){
	var obj = ZD.ux.GetGridData(table);
	var Rdata=[];
	var data = null;
	if(obj.data.data){
		data = obj.data.data;
	}else{
		data = obj.data;
	}
	var fids = ZD.ux.SelectedCheckboxIds(table);
	if(fids.length == 0){
		return null;
	}
	
	var fid=fids.split(",");
	for(var i=0;i<data.length;i++){
		for(var j=0;j<fid.length;j++)
		{
			if(data[i][ZD.base.ID] == fid[j]){
				Rdata[j]=data[i];
			}
		}
	}
	return Rdata;
}

/*删除行对象
 * fid:要删除的主键值
 * primary:主键名称
 * */
ZD.ux.DeleteGridRow = function(table,fid,primary){
	var obj = ZD.ux.GetGridData(table);
	var data = null;
	var fl = false; //是否分页
	if(obj.data.data){
		data = obj.data.data;
		fl = true;
	}else{
		data = obj.data;
		fl = false;
	}
	if(!primary){
		primary = ZD.base.ID;
	}
	var row = null;
	for(var i=0;i<data.length;i++){
		for(var item in data[i]){
			if(item == primary && fid == data[i][item]){
				row = data[i];
				data.splice(i,1); //移除行对象
				break;
			}
		}
	}
	if(row != null){
		if(fl){
			obj.data.data = data;
		}else{
			obj.data = data;
		}
		ZD.ux.BindGrid({
			table:table,
			paging:fl,
			staticdata:obj
		});
	}
}

/*得到复选框选中的Ids*/
ZD.ux.SelectedCheckboxIds = function(table){
	var fids = '';
	$('#'+table).find("input[name='ids']").each(function(){
		if(this.checked){
			if(fids.length == 0){
				fids = $(this).val();
			}else{
				fids += ',' + $(this).val();
			}
		}
	});
	return fids;
}

/*得到复选框选中的行数*/
ZD.ux.SelectedCheckboxCount = function(table){
	var fcount = 0;
	$('#'+table).find("input[name='ids']").each(function(){
		if(this.checked){
			fcount++;
		}
	});
	return fcount;
}

/*遍历对象的属性和值，设置页面的值(用于修改)--前提是页面的ID与对象属性一一对应,scope范围(支持ID选择器和class选择器例如：#model，.model)*/
ZD.ux.InitInputValue = function(obj,scope){
	scope = scope||"";
	if(scope.length > 0){
		scope = scope + " ";
	}
	for(var item in obj){
		//属性 赋值...优先级 低 
		if($(scope+"[data-id='"+item+"']").is("div")){
			if($(scope+"[data-id='"+item+"']").attr("data-input")){
				$(scope+"[data-id='"+item+"']").summernote("code",obj[item]);
			}
		}else if($(scope+"[data-id='"+item+"']").attr("type") == "checkbox"){
			if(obj[item] == "1"){
				$(scope+"[data-id='"+item+"']").prop("checked","checked");
			}else{
				$(scope+"[data-id='"+item+"']").prop("checked","");
			}
		}else{
			$(scope+"[data-id='"+item+"']").val(obj[item]);
			if($(scope+"[data-id='"+item+"']").is("select")){
				$(scope+"[data-id='"+item+"']").selectpicker('refresh');
				$(scope+"[data-id='"+item+"']").change();
			}
		}
		
		// ID 赋值... 优先级 高
		if($("#"+item).is("div")){
			if($("#"+item).attr("data-input")){
				$("#"+item).summernote("code",obj[item]);
			}
		}else if($("#"+item).attr("type") == "checkbox"){
			if(obj[item] == "1"){
				$("#"+item).prop("checked","checked");
			}else{
				$("#"+item).prop("checked","");
			}
		}else{
			$("#"+item).val(obj[item]);
			if($("#"+item).is("select")){
				//$("#"+item).selectpicker('refresh');
				$("#"+item).change();
			}
		}
	}
}

/*遍历 input标签 拼接json对象(对象的属性就是inpu的id,值是val)*/
ZD.ux.GetInputValue = function(a){
	var fdata = {};
	$(a+" input,"+a+" select,"+a+" div, " + a + " textarea").each(function(){
		var f1 = $(this).attr("id"); //ID 属性选择 优先级 高
		if(!f1){ 
			f1 = $(this).attr("data-id"); //data-id 属性选择 低
		}
		if(!f1 || f1.indexOf("_table_data") > -1){
			return true; //结束当前循环
		}
		//遍历值 拼接json对象
		if($(this).is("div")){
			if($(this).attr("data-input")){
				var fval = $(this).summernote("code");
				fdata[f1] = fval;
			}
		}else if($(this).attr("type") == "checkbox"){
			//是否选中 用1和0表示
			var fval = $(this).is(':checked');
			if(fval){
				fdata[f1] = 1;
			}else{
				fdata[f1] = 0;
			}
		}else{
			var fval = $(this).val();
			fdata[f1] = fval;
			
			//复制数字框
			if($(this).attr("type") == "number" && fval.length == 0){
				fdata[f1] = 0;
			}
		}
	});
	return fdata;
}

/*清空 input值 (用于弹窗便后的新增)*/
ZD.ux.ClearInputValue = function(a){
	var fdata = {};
	$(a+" input,"+a+" select,"+a+" div, " + a + " textarea").each(function(){
		if($(this).is("select")){
			$(this).val(" ");
			//$(this).selectpicker("refresh");
		}else if($(this).is("div")){
			if($(this).attr("data-input")){
				$(this).summernote("code","");
			}
		}else if($(this).attr("type") == "checkbox"){
			var fdefault = $(this).attr("data-default");
			if(fdefault == "1"){
				$(this).prop("checked","checked");
			}else{
				$(this).prop("checked","");
			}
		}else if($(this).attr("type") == "number"){
			$(this).val("0");
		}else{
			$(this).val("");
		}
	});
	return fdata;
}

/*初始化下拉框-（bootstrap-select）*/
ZD.ux.InitSelect = function(option){
	var _obj = $("#"+option.select);
	if(_obj == null || !_obj){
		_obj = $("[data-id='"+option.select+"']");
	}
	var _html = _obj.html();
	if(!_html){
		_obj = $("[data-id='"+option.select+"']");
		_html = $("[data-id='"+option.select+"']").html();
	}
	/*缓存 html模板*/
	if(ZD.base.Template[option.select] == undefined){
		ZD.base.Template[option.select] = _html;
	}else{
		_html = ZD.base.Template[option.select];
	}
	/*移除模板...*/
	_obj.html("<option value=' ' selected='selected' ></option>");
	
	/*成功后执行的方法*/
	option.success = function(res){
		if(res.status == 0){
			var html;
			if(res.data.data){
				html = ZD.ux.Rephtml(res.data.data, _html);
			}else{
				html = ZD.ux.Rephtml(res.data, _html);
			}
			
			if(option.addOptions) {
				for(var i = 0; i < option.addOptions.length; i++){
					html = '<option value="'+option.addOptions[i].value+'" >'+option.addOptions[i].name+'</option>' + html;
				}
			}
			
			if(!option.unselected && option.unselected != false){
				html = '<option value=" " selected="selected" >--未选择--</option>' + html;
			}
			
			_obj.html(html);
			/*设置值...*/
			if(option.val){
				_obj.val(option.val);
			}
			
			if(option.callback){
				option.callback(res);
			}
		//	_obj.selectpicker('refresh');
		}
	}
	ZD.ux.Ajax(option);
}

/*选中下拉框*/
ZD.ux.SelectDataValue = function(option){
	var objs = $("#"+option.id+" option");
	for(var i=0;i<objs.length;i++){
		//console.log(objs.eq(i).attr("data-value"));
		if(objs.eq(i).attr("data-value") == option.val){
			$("#"+option.id).val(objs.eq(i).attr("value"));
			$("#"+option.id).selectpicker('refresh');
			break;
		}
	}
}

/*初始化分类下拉框-（bootstrap-select）*/
ZD.ux.InitSortSelect = function(option){
	var _obj = $("#"+option.select);
	if(!_obj){
		_obj = $("[data-id='"+option.select+"']");
	}
	var _html = _obj.html();
	if(!_html){
		_obj = $("[data-id='"+option.select+"']");
		_html = $("[data-id='"+option.select+"']").html();
	}
	var pId = 'pId';
	var id = 'id';
	if(option.key){
		id = option.key.idKey == undefined ? "id" : option.key.idKey;
		pId = option.key.pIdKey == undefined ? "pId" : option.key.pIdKey;
	}
	
//	var _phmlt = $(_obj.children().prop('outerHTML')).empty()[0].outerHTML;
	var _phmlt = $(_html.replace(/(^\s*)|(\s*$)/g,"")).empty()[0].outerHTML;
	var _chtml = _obj.children().html().replace(/(^\s*)|(\s*$)/g,"");

	/*成功后执行的方法*/
	option.success = function(res){
		
		if(res.status == 0){
			var html;
			var data = [];
			if(res.data.data){
				data = res.data.data;
			}else{
				data = res.data;
			}
			var reg = /{{([A-Za-z0-9_]+)}}/gm;
			var html = '';
			var phtml = '';
			var chtml = '';
			for(var i = 0; i < data.length; i++){
				if(data[i][pId] == '0'){
					phtml = _phmlt.replace(reg,function(patt, $1){
						return (data[i][$1]==null || data[i][$1]==undefined ? "":data[i][$1]);
					});
					chtml = '';
					//console.log(data);
					for(var j = 0; j < data.length; j++){
						if(data[i][id] == data[j][pId]){
							chtml += _chtml.replace(reg,function(patt, $1){
								return (data[j][$1]==null || data[j][$1]==undefined ? "":data[j][$1]);
							});
						}
					}
					//console.log(chtml);
					html += $(phtml).append(chtml).prop('outerHTML');
				}
			}
			html = '<option value=" " selected="selected" >--未选择--</option>' + html;
			_obj.empty();
			_obj.append(html);
			/*设置值...*/
			if(option.val){
				_obj.val(option.val);
			}
			_obj.selectpicker('refresh');
		}
	};
	ZD.ux.Ajax(option);
};

/* 功能：初始化 html文本框 
 * 参数：el：文本框的选择器对象(必需,例如：.summernote)
 * 条件：需引用 summernote/summernote.css、summernote/summernote.min.js、summernote/lang/summernote-zh-CN.min.js
 * */
ZD.ux.SummerNote = function(option){
	var $this = $(option.el); /*html文本框对象*/
	var minHeight = option.minHeight || 200; /*最小高度*/
	$this.each(function() {
        $(this).summernote({
        	toolbar : [['edit',['undo','redo']],
			            ['headline', ['style']],
			            ['style', ['bold', 'italic', 'underline', 'superscript', 'subscript', 'strikethrough', 'clear']],
			            ['fontface', ['fontname']],
			            ['textsize', ['fontsize']],
			            ['fontclr', ['color']],
			            ['alignment', ['ul', 'ol', 'paragraph', 'lineheight']],
			            ['height', ['height']],
			            ['table', ['table']],
			            ['insert', ['link','picture','video','hr']],
			            ['view', ['fullscreen', 'codeview']],
			            ['help', ['help']]
			        ],
            lang : "zh-CN",
            minHeight : minHeight,
            dialogsFade : true,
            dialogsInBody : true,
            disableDragAndDrop : false,
            callbacks:{
            	onImageUpload:function(files){
            		for(var i=0;i<files.length;i++){
            			var imageUrl = files[i].url;
            			
            			//前缀
            			var protocol = window.location.protocol;
            			var host = window.location.host;
            			var url = protocol + '//' + host + '/cunfang/'; //头部
            			
                    	$this.summernote("insertImage", url+imageUrl, function($image){
                    		$image.css({"width":"100%"});
                    	});
            		}
            	}
            }
        });
    });
	
}

/*基于后端 springMVC的上传文件功能
 * option.url 上传文件的url，option.file 文件流($("#user_file").prop("files")[0])，option.callback 回调
 * */
ZD.ux.Upload = function(option){
	/*模拟窗体提交文件...*/
	var data = new FormData();
	data.append("file", option.file);
	$.ajax({
        data : data,
        type : "POST",
        url : option.url,
        cache : false,
        contentType : false,
        processData : false,
        beforeSend:function(request){
			request.setRequestHeader("token", ZD.ux.GetCookie(ZD.base.TOKEN));
		},
        success : function(res) {
        	var json = eval("("+res+")");
        	/*执行回调...*/
        	if(option.callback){
        		option.callback(json);
        	}
        }
    });
}

/*
 * 加载权限记录...
 * 【页面加载完成后调用】
 * */
ZD.ux.InitRightInfo = function(){
	/*当前页面*/
	var fid = parent.CurrPageID;
	if(!fid){
		fid = window.CurrPageUrl;
	}
	
	/*权限对象*/
	var rights = parent.CurrRights;
	if(!rights){
		rights = window.CurrRights;
	}
	
	/*遍历权限 监听单击事件*/
	for(var i=0;i<rights.length;i++){
		/*找到功能项...*/
		if(fid == rights[i].page_id){
			var Code = rights[i].func_code;
			var Check = rights[i].fcheck;
			/*绑定单击事件...*/
			$("#"+Code).bind("click",{Code:Code,Check:Check},function(event,code){
				/*无权操作*/
				if(event.data.Check != '1'){
					ZD.msg.alert('<span style="color:red;">您没有权限进行此项操作.</span>');
					return;
				}
				
				/*有权操作*/
				var code = event.data.Code;
				if($("#"+code).attr("data-click")){
					code = $("#"+code).attr("data-click");
				}else{
					code = code+'()';
				}
				eval(code);
			});
			
			/*隐藏 无权限按钮*/
			if(Check != '1' && ZD.base.RightFuncHide){
				$("#"+Code).hide();
			}
		}
	}
}

/*把json对象转成字符串--暂时只支持一维*/
ZD.ux.toJSONString = function(_obj){
	var str = "{";
	for(var item in _obj){
		if(str.length > 1){
			str += ",'"+item+"':'"+_obj[item]+"'";
		}else{
			str += "'"+item+"':'"+_obj[item]+"'";
		}
	}
	str += "}";
	return str;
}

/*把图片对象转换成 base64*/
ZD.ux.GetBase64Image = function(img){
	 var canvas = document.createElement("canvas");
     canvas.width = img.width;
     canvas.height = img.height;
     var ctx = canvas.getContext("2d");
     ctx.drawImage(img, 0, 0, img.width, img.height);
     var ext = img.src.substring(img.src.lastIndexOf(".")+1).toLowerCase();
     var dataURL = canvas.toDataURL("image/"+ext);
     return dataURL;
}


/*======================方法部分 end============================*/

/*======================消息框 start============================*/
ZD.msg = {};

/*消息框的基础html*/
ZD.msg.base = '<div id="_zd_dig_0" style="z-index:1500" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">'+
'<div class="modal-dialog" role="document"><div class="modal-content"><div class="modal-header">'+
'<button type="button" class="close" data-dismiss="modal" aria-label="Close" id="_zd_colse_0"><span aria-hidden="true">×</span></button>'+
'<h4 class="modal-title" id="_zd_title_0">${title}</h4></div>'+
'<div class="modal-body" id="_zd_text_0">${text}</div><div class="modal-footer">'+
'<button type="button" class="btn btn-default" data-dismiss="modal" id="_zd_button_0">${canel}</button>'+
'<button type="button" class="btn btn-primary" data-dismiss="modal" id="_zd_button_1">${ok}</button>'+
'</div></div></div></div>';

/*普通的消息框*/
ZD.msg.alert = function(msg,func,func1){
	var option = {};
	option.title = "消息";
	option.text = msg;
	option.showcanel = false;
	option.showcanel_text = "关闭";
	option.showok = true;
	option.showok_text = "知道了";
	option.callback = func;
	option.callback_close = func1;
	ZD.msg.show(option);
}

/*自动取消的消息框*/
ZD.msg._autodialog_timeout = null;
ZD.msg.auto = function(msg,time,func){
	ZD.msg.alert(msg,func);
	var remaining = time || 4;
	var obj = document.getElementById("_zd_text_0");
	ZD.msg._autodialog_timeout = window.setInterval(function(){
        remaining--;
        if(remaining <= 0) {
            window.clearInterval(ZD.msg._autodialog_timeout);
            ZD.msg._autodialog_timeout = null;
            $("#_zd_button_1").click();
        }
        obj.innerHTML = msg + '<br /><span style="color:red;">' + remaining + '</span> 秒后关闭';
    }, 1000);
}

/*确定和取消的对话框*/
ZD.msg.confirm = function(msg,func){
	var option = {};
	option.title = "询问";
	option.text = msg;
	option.showcanel = true;
	option.showcanel_text = "取消";
	option.showok = true;
	option.showok_text = "确定";
	option.callback = func;
	ZD.msg.show(option);
}

/*自动关闭 等待框(单位：毫秒)
 * t:自动关闭的时间，默认不关闭
 * */
ZD.msg.load = function(t){
	var l = null;
	if(t){
		l = layer.load(1,{shade: [0.1,"#000000"],time:t});
	}else{
		l = layer.load(1,{shade: [0.1,"#000000"]});
	}
	return l;
}

/*
 * 关闭loading
 * */
ZD.msg.close = function(l){
	if(l){
		layer.close(l);
	}
}

/*显示消息框*/
ZD.msg.show = function(option){
	$("#_zd_dig_0").remove();
	$("body").append(ZD.msg.base);
	$("#_zd_title_0").text(option.title);
	$("#_zd_text_0").html(option.text);
	$("#_zd_button_0").text(option.showcanel_text);
	$("#_zd_button_1").text(option.showok_text);
	if(!option.showcanel){
		$("#_zd_button_0").hide();
	}
	if(!option.showok){
		$("#_zd_button_1").hide();
	}
	$("#_zd_dig_0").modal();
	
	//关闭
	$("#_zd_colse_0").click(function(){
		if(option.callback_close){
			option.callback_close();
		}
	});
	
	//确定
	$("#_zd_button_1").click(function(){
		if(option.callback){
			option.callback();
		}
	});
}

/*======================消息框 end============================*/


/*======================正则表达式 start============================*/
ZD.verify = {};

/*根据key找到正则的value*/
ZD.verify.Range = function(name){
	for(var i=0;i<ZD.verify.Regular.length;i++){
		if(ZD.verify.Regular[i].key == name){
			return ZD.verify.Regular[i].value;
		}
	}
	return "";
}

/*正则表达式的对象*/
ZD.verify.Regular = [
                     {key:"Empty",value:/\S/},/*判断空*/
                     {},
                     {}
                    ];

/*======================正则表达式 end============================*/


/*======================日期控件 start============================*/
/* 功能：日期控件 
 * 参数：
 * 	config.name : 需要初始化为日期控件的 input id 可以多个 ['a', 'b', 'c']
 *	config.timePicker : 是否显示时间选择，默认false 注意：如果config.dataRange为true，该参数无效
 *	config.dataRange : 是否使用间隔日期（日期区间），默认 false 
 *	config.fromTo : 需要使用间隔日期的两个input id [{'开始日期', '结束日期'}] 可以多组，注意：这里设置的id必须要在config.name中设置
 * 条件：需引用 dhtmlxCalendar/fonts/font_roboto/roboto.css、
 * 			dhtmlxCalendar/dhtmlxcalendar.css、
 * 			dhtmlxCalendar/dhtmlxcalendar.min.js
 * */
ZD.calendar = {};
ZD.calendar.init = function(config){
	if(!config)
		return;
	if(!config.name)
		return;
	var myCalendar = new dhtmlXCalendarObject(config.name);
	//汉化
	dhtmlXCalendarObject.prototype.langData["zh-CN"] = {
	        dateformat: "%Y-%m-%d %H:%i:%s",
	        hdrformat: "%F %Y",
	        monthesFNames: ["一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"],
	        monthesSNames: ["一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"],
	        daysFNames: ["星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"],
	        daysSNames: ["日", "一", "二", "三", "四", "五", "六"],
	        weekstart: 7,//一周的开始天
	        weekname: "周",
	        today: "今天",
	        clear: "清除"
    	};
	
	if(config.dataRange)
		config.timePicker = false;
	
	if(!config.timePicker && config.timePicker != 'true'){
		myCalendar.hideTime();
		dhtmlXCalendarObject.prototype.langData["zh-CN"].dateformat = '%Y-%m-%d';
	}
	
	if(config.dateformat) {
		dhtmlXCalendarObject.prototype.langData["zh-CN"].dateformat = config.dateformat;
	}
	
    myCalendar.loadUserLanguage('zh-CN');
    myCalendar.setMinutesInterval(1);
    
    
    myCalendar.showToday();
    
    var myEvent = myCalendar.attachEvent("onClick", function(){
        // your code here
    });
    
    //日期区间
    var date = new Date();
    var seperator1 = "-";
    var seperator2 = ":";
    var month = date.getMonth() + 1;
    var strDate = date.getDate();
    if (month >= 1 && month <= 9) {
        month = "0" + month;
    }
    if (strDate >= 0 && strDate <= 9) {
        strDate = "0" + strDate;
    }
    var currentdate = date.getFullYear() + seperator1 + month + seperator1 + strDate;
//            + " " + date.getHours() + seperator2 + date.getMinutes()
//            + seperator2 + date.getSeconds();
    
    if(config.dataRange && config.fromTo){
    	for(var i = 0; i < config.fromTo.length; i++){
    		var from = config.fromTo[i].from;
    		var to = config.fromTo[i].to;
    		$('#'+from).val(currentdate);
    		$('#'+to).val(currentdate);
    		
			$('#'+from).click(function(){
				myCalendar.setSensitiveRange(null, $('#'+to).val());
				
			});
			$('#'+to).click(function(){
				myCalendar.setSensitiveRange($('#'+from).val(), null);
				
			});
    	}
    	
    }
    
};

/*======================日期控件 end============================*/


/*======================popover弹窗 start============================
 * obj:jquery对象，弹窗的显示处(以后用此，不要用ZD.ux.popover)
 * */
ZD.ux.upopover = function(config){
	var _obj = null;
	if(config.obj){
		_obj = config.obj;
	}else{
		_obj = $("#" + config.name);
	}
	var _content = $('#' + config.content).html();
	
	var _html = '<div class="text-right"><button class="btn btn-default _popover_close_1" type="button" style="margin-right:2px;">关闭</button><button class="btn btn-primary _popover_ok_1" type="button">确定</button></div>';
	_content = '<div class="_popover_div_1">' + _content + _html +"</div>";
	_obj.popover({
		trigger:"click",
	    html:true,
	    title:config.title == undefined ? "提示" : config.title,
	    content:_content
	});
	
	_obj.on('shown.bs.popover', function (e) {
		//关闭
		$("._popover_close_1").click(function(){
			_obj.popover("hide");
		});
		//确定
		if(config.callback){
			var fthis = $(this);
			$("._popover_ok_1").unbind("click").click(function(e1){
				/*正则验证*/
				if(!ZD.ux.Verify("._popover_div_1")){
					return false;
				}
				var fdata = ZD.ux.GetInputValue("._popover_div_1");
				config.callback(fdata,fthis);
				
				//隐藏弹窗...
				_obj.popover("hide");
			});
		}
		
		//显示后发送的方法
		if(config.showCallback){
			config.showCallback(config.data);
		}
    });
	
};

/**兼容的老版...........**/
ZD.ux.popover = function(config){
	var _obj = $('#' + config.name);
	var _content = $('#' + config.content);
	
	_obj.popover({
		animation : true,
	    //trigger : "focus",    //如果设为focus 当按钮失去焦点提示层会消失，例如页面空白处单机提示层消失
	    placement : config.placement == undefined ? 'bottom' : config.placement,
	    html:true,
	    title : config.title == undefined ? '提示' : config.title,
//	    content : _obj.prop('outerHTML')
	    content : _content.html()
	}); 
	
	_obj.on('shown.bs.popover', function () {
		if(config.showCallback)
			config.showCallback(config.data);
	});
};

/*======================popover弹窗 end============================*/

/*======================自动循环设置参数 start============================*/
ZD.ux.repeat = function(config){
	var _obj = $("#"+config.name);
	var _html = _obj.html();
	if(ZD.base.Template[config.name] == undefined){
		ZD.base.Template[config.name] = _html;
	}else{
		_html = ZD.base.Template[config.name];
	}
	
	/*成功后执行的方法*/
	config.success = function(res){
		if(res.status == 0){
			var html;
			if(res.data.data){
				html = ZD.ux.Rephtml(res.data.data, _html);
			}else{
				html = ZD.ux.Rephtml(res.data, _html);
			}
			
			_obj.html(html);
			if(config.callback)
				config.callback(res);
		}
	};
	ZD.ux.Ajax(config);
};
/*======================自动循环设置参数 end============================*/



